import { uniqWith, unionBy, cloneDeep, constant } from '@alipay/bigfish/util/lodash';

export const loopAddChild = (originArr, selectKey, addArr) => {
  let newOriginArr = [...originArr];
  newOriginArr.forEach((v) => {
    if (v.key == selectKey) {
      if (!v.children || !v.children.length) {
        return (v.children = addArr);
      } else if (v?.children && v.children.length) {
        let oldChildren = v.children;
        let newAddArr = addArr.map((item) => {
          let tarObj = oldChildren.find((c) => c.key === item.key);
          if (tarObj) return { ...item, children: tarObj.children };
          return { ...item };
        });
        v.children = newAddArr;
      }
    } else {
      v?.children && v.children.length && loopAddChild(v.children, selectKey, addArr);
    }

    return newOriginArr;
  });
};

export const updateTreeData = (list, key, children) =>
  list.map((node) => {
    if (node.key === key) {
      return {
        ...node,
        children,
      };
    }
    if (node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children),
      };
    }
    return node;
  });

export function getTreeItem(data, id) {
  let result = null;
  function loop(arr, key) {
    arr.forEach((item) => {
      if (item.key === key) {
        result = item;
      } else {
        if (item.children) {
          loop(item.children, id);
        }
      }
    });
  }

  loop(data, id);
  return result;
}

// 将树形节点改为一维数组 children版本
export const generateList = (data, dataList) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    dataList.push({ ...node });
    if (node.children) {
      generateList(node.children, dataList);
    }
  }
  return dataList;
};

// 将树形节点改为一维数组  suborgs版本
export const generateSubOrgList = (data, dataList) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    dataList.push({ ...node });
    if (node.subOrgs) {
      generateSubOrgList(node.subOrgs, dataList);
    }
  }
  return dataList;
};

export const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

//无id 树形数据替换参数and删除key值 入参处理
export const replaceParam = (data) => {
  let item = [];
  data.map((list, i) => {
    let newData = { ...list };
    // newData.name = list.title;
    if (list.children) {
      newData.subOrgs = replaceParam(list.children);
    }
    delete newData.key;
    // delete newData.title;
    delete newData.children;
    delete newData.level;
    item.push(newData);
  });
  return item;
};

//已有id
export const translateParams = (data) => {
  let item = [];
  data.map((list, i) => {
    let newData = { ...list };
    // newData.id = list.key;
    // newData.name = list.title;
    if (list.children) {
      newData.subOrgs = translateParams(list.children);
    }
    delete newData.key;
    // delete newData.title;
    delete newData.children;
    item.push(newData);
  });
  return item;
};

//编辑处理入参 添加to_delete_flag
export const editResponseParam = (data) => {
  let item = [];
  data.map((list, i) => {
    let newData = { ...list };
    newData.key = `${list.id}-${i}`;
    if (list.subOrgs) {
      newData.children = editResponseParam(list.subOrgs);
    }
    // delete newData.name;
    delete newData.subOrgs;
    item.push(newData);
  });
  return item;
};

//接口返回的数据 转化为替换成树形需要的字段名 出参处理  data为需要修改的tree，适配antd3树形数据结构
export const responseReplaceParams = (data) => {
  let item = [];
  data.map((list, i) => {
    let newData = { ...list };
    newData.key = `${list.id}-${i}`;
    // newData.title = list.name;
    if (list.subOrgs) {
      newData.children = responseReplaceParams(list.subOrgs);
    }
    // delete newData.name;
    delete newData.subOrgs;
    item.push(newData);
  });
  return item;
};

const cover = (arr1, arr2) => {
  let arrayOne = arr1.filter((item) => {
    return !arr2.some((v) => v.serviceId === item.serviceId);
  });
  let newValue = arrayOne.concat(arr2);
  return newValue;
};

//添加服务授权
export const addServiceList = (originArr, selectKey, addArr) => {
  originArr.forEach((v) => {
    if (v.key == selectKey) {
      v.serviceAuthList = v.serviceAuthList ? cover(v.serviceAuthList, addArr) : addArr;
    } else {
      v?.children && addServiceList(v.children, selectKey, addArr);
    }
  });
};

//父级服务[
export const parentCover = (arr1, arr2) => {
  let newArr2 = arr2.filter((item) => {
    return !arr1.some((v) => v.serviceId === item.serviceId);
  });
  let newArr1 = arr1.map((v) => {
    let targetObj = arr2.find((item) => item.serviceId === v.serviceId);
    if (targetObj) {
      return v?.toDeleteFlag === true ? { ...v, ...targetObj } : { ...targetObj, ...v };
    } else {
      return v;
    }
  });

  return newArr1.concat(newArr2);
};

//父级添加服务授权
export const addParentServiceList = (originArr, selectKey, addArr) => {
  originArr.forEach((v) => {
    if (v.key == selectKey) {
      v.serviceAuthList = v.serviceAuthList ? parentCover(v.serviceAuthList, addArr) : addArr;
    } else {
      v?.children && addParentServiceList(v.children, selectKey, addArr);
    }
  });
};

//删除服务授权
export const deleteServiceList = (originArr, selectKey, addArr) => {
  originArr.forEach((v) => {
    if (v.key == selectKey) {
      v.serviceAuthList = addArr;
    } else {
      v?.children && deleteServiceList(v.children, selectKey, addArr);
    }
  });
};

//查找机构服务授权列表
export const queryServiceList = (originArr, selectKey) => {
  for (let i = 0; i < originArr.length; i++) {
    const node = originArr[i];
    if (node.key === selectKey && node.serviceAuthList) {
      return node.serviceAuthList;
    } else {
      if (node.children) {
        let res = queryServiceList(node.children, selectKey);
        if (res.length) return res;
      }
    }
  }

  return [];
};

//查找选中节点机构所有信息
export const querySelectedNodeInfo = (originArr, selectKey) => {
  for (let i = 0; i < originArr.length; i++) {
    const node = originArr[i];
    if (node.key === selectKey) {
      return node;
    } else {
      if (node?.children) {
        let res = querySelectedNodeInfo(node.children, selectKey);
        if (res) return res;
      }
    }
  }
  return null;
};

//添加服务字段配置
export const addDeployInfo = (originArr, selectKey, addArr) => {
  // let newOriginArr = cloneDeep(originArr);
  originArr.forEach((v) => {
    if (v.key == selectKey) {
      v.serviceAuthList = addArr;
    } else {
      v?.children && addDeployInfo(v.children, selectKey, addArr);
    }
  });
};

//省略号//截取字符串中间用省略号显示
export const getSubStr = (str) => {
  if (!str?.length) return '';
  if (str?.length > 10) {
    let subStr1 = str.substr(0, 5);
    let subStr2 = str.substr(str.length - 5, 5);
    let subStr = subStr1 + '********' + subStr2;
    return subStr;
  } else if (str?.length < 10 && str?.length > 1) {
    let subStr1 = str.substr(0, 1);
    let subStr2 = str.substr(str.length - 1, 1);
    let subStr = subStr1 + '********' + subStr2;
    return subStr;
  } else {
    return str;
  }
};

//标记层级
export const calculateLevel = (arr, initLevel) => {
  arr.forEach((element) => {
    element.level = initLevel;
    if (element.children) {
      calculateLevel(element.children, initLevel + 1);
    }
  });
  return arr;
};

//递归过滤树形
export const deepFilter = (list) => {
  return list.filter((item) => {
    if (item.children) {
      item.children = deepFilter(item.children);
    }
    return item.toDeleteFlag !== true;
  });
};

//给顶层父机构添加服务授权
export const addTopParentDataService = (tree, value) => {
  if (tree.length <= 0) return tree;
  let newTree = cloneDeep(tree);
  let serviceAuthList = newTree[0]?.serviceAuthList
    ? newTree[0].serviceAuthList.concat(value)
    : value;
  serviceAuthList = unionBy(serviceAuthList, 'serviceId');
  newTree[0].serviceAuthList = serviceAuthList;
  return newTree;
};

//给顶层父机构删除服务授权，子机构联动也要删除
export const cancelParentDataService = (tree, serviceId) => {
  tree.forEach((v) => {
    if (v.serviceAuthList?.length) {
      v.serviceAuthList = v.serviceAuthList.filter((item) => item.serviceId !== serviceId);
    }
    if (v?.children?.length) {
      cancelParentDataService(v.children, serviceId);
    }
  });
  return tree;
};

//根据key 查找所有父级节点
export function getParentIds(data, key) {
  // 深度遍历查找
  function dfs(data, key, parents) {
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      // 找到key则返回父级key
      if (item.key === key) return parents;
      // children不存在或为空则不递归
      if (!item.children || !item.children.length) continue;
      // 往下查找时将当前key入栈
      parents.push(item.key);

      if (dfs(item.children, key, parents).length) return parents;
      // 深度遍历查找未找到时当前key 出栈
      parents.pop();
    }
    // 未找到时返回空数组
    return [];
  }

  return dfs(data, key, []);
}

//校验机构的授权服务是否全部进行了服务配置
//authorizationDetails  outputAllProperty  target为【需要收集的数组】
const checkDeploy = (tree, target) => {
  tree.map((v) => {
    if (v.serviceAuthList?.length) {
      let targetObj = v?.serviceAuthList.find(
        (item) => !item.authorizationDetails || !item.outputAllProperty,
      );
      if (targetObj) {
        console.log(targetObj, v, 12345678);
        target.push(v);
      }
      if (v.children || v.children?.length) {
        checkDeploy(v.children, target);
      }
    } else {
      return target.push(v);
    }
  });
  return target;
};

//删除空节点 subOrgs
export const deleteEmpty = (list) => {
  if (!list) return;
  list.forEach((item) => {
    if ('subOrgs' in item && item?.subOrgs?.length === 0) {
      delete item.subOrgs;
    } else if ('subOrgs' in item && item?.subOrgs?.length) {
      deleteEmpty(item.subOrgs);
    }
  });
};

//删除空节点 children
export const deleteChildEmpty = (list) => {
  if (!list) return;
  list.forEach((item) => {
    if ('children' in item && item?.children?.length === 0) {
      delete item.children;
    } else if ('children' in item && item?.children?.length) {
      deleteChildEmpty(item.children);
    }
  });
};

//修改模式下，toDeleteFlag置为true 给顶层父机构删除服务授权，子机构联动也要删除
export const cancelEditModeParentDataService = (tree, serviceId) => {
  tree.forEach((v) => {
    if (v.serviceAuthList?.length) {
      v.serviceAuthList = v.serviceAuthList.map((item) => {
        if (item.serviceId === serviceId) {
          return { ...item, toDeleteFlag: true };
        } else {
          return item;
        }
      });
    }
    if (v?.children?.length) {
      cancelEditModeParentDataService(v.children, serviceId);
    }
  });
  return tree;
};

//替换节点
export const changeChild = (originArr, selectKey, addArr) => {
  if (!originArr || !originArr.length) return;
  for (let i = 0; i < originArr.length; i++) {
    let node = originArr[i];
    if (node.key == selectKey) {
      node = addArr;
    } else {
      node?.children && changeChild(node?.children, selectKey, addArr);
    }
  }
};

//查找树形所有的id
function lookForAllId(data = [], arr = []) {
  for (let item of data) {
    arr.push(item.id);
    if (item.children && item.children.length) lookForAllId(item.children, arr);
  }
  return arr;
}

//查找树形下的serviceId
export const lookServiceId = (tree, arr = []) => {
  for (let item of tree) {
    if (item?.serviceAuthList) {
      let newArr = item?.serviceAuthList.map((v) => v.serviceId);
      arr.push();
    }
    if (item.children && item.children.length) lookServiceId(item.children, arr);
  }
  return arr;
};

//修改模式删除父服务联动子服务删除
const loopSub = (data1, serviceId) => {
  let data = cloneDeep(data1);
  data.forEach((v) => {
    if (v.serviceAuthList?.length) {
      v.serviceAuthList = v.serviceAuthList.map((item) => {
        if (item.serviceId == serviceId) {
          return { ...item, toDeleteFlag: true };
        } else {
          return item;
        }
      });
    }
    if (v.children) {
      let a = loopSub(v.children, serviceId);
      v.children = a;
    }
  });
  console.log(data, 'data');
  return data;
};
export const cancelModeParentDataService = (tree, key, serviceId) => {
  let xxx = cloneDeep(tree);
  for (let i = 0; i < tree.length; i++) {
    let node = tree[i];
    console.log(node, key, '节点');
    if (node.key === key) {
      let res = loopSub([{ ...node }], serviceId);
      xxx[i] = res[0];
      return xxx;
    } else {
      if (node.children) {
        let b = cancelModeParentDataService(node.children, key, serviceId);
        xxx[i].children = b;
        return xxx;
      }
    }
  }
};

const createLoop = (data1, serviceId) => {
  let data = cloneDeep(data1);
  data.forEach((v) => {
    if (v.serviceAuthList?.length) {
      v.serviceAuthList = v.serviceAuthList.filter((item) => item.serviceId !== serviceId);
    }
    if (v.children) {
      let a = createLoop(v.children, serviceId);
      v.children = a;
    }
  });
  return data;
};
export const cancelCreateModeParentDataService = (tree, key, serviceId) => {
  let xxx = cloneDeep(tree);
  for (let i = 0; i < tree.length; i++) {
    let node = tree[i];
    if (node.key === key) {
      let res = createLoop([{ ...node }], serviceId);
      xxx[i] = res[0];
      return xxx;
    } else {
      if (node.children) {
        let b = cancelCreateModeParentDataService(node.children, key, serviceId);
        xxx[i].children = b;
        return xxx;
      }
    }
  }
};

//更换旧serviceId
export const changeServiceId = (originArr, selectKey, oldService, newServiceId) => {
  console.log(oldService, newServiceId, 'oldService, newServiceId');
  originArr.forEach((v) => {
    if (v.key == selectKey) {
      v.serviceAuthList = v.serviceAuthList.map((item) => {
        if (item.serviceId === oldService) {
          return { ...item, serviceId: newServiceId };
        } else {
          return item;
        }
      });
    } else {
      v?.children && changeServiceId(v.children, selectKey, oldService, newServiceId);
    }
  });
};

export const changeSubChild = (originArr, selectKey, addArr) => {
  originArr.forEach((v) => {
    if (v.key == selectKey) {
      v.children = addArr;
    } else {
      v.children && changeSubChild(v.children, selectKey, addArr);
    }
  });
};

//对象比较 浅比较，第一层
export function isObjShallowEqual(obj1, obj2) {
  const keys1 = Object.getOwnPropertyNames(obj1);
  const keys2 = Object.getOwnPropertyNames(obj2);
  if (keys1.length !== keys2.length) {
    return false;
  }
  const flag = keys1.every((key) => {
    const type = typeof obj1[key];
    // do not check function, array, object
    if (['function', 'array', 'object'].includes(type)) {
      return type === typeof obj2[key];
    }
    // if unequal, return true
    if (obj1[key] !== obj2[key]) {
      return false;
    }
    return true;
  });
  // if found unequal, then return false, which means unequal
  return flag;
}

//获取选中节点及其子节点
export const getNodeChildId = (tree, currentId, childNodeId = []) => {
  for (let i = 0; i < tree.length; i++) {
    let node = tree[i];
    if (node.key === currentId) {
      childNodeId.push(node.key);
      if (node?.children?.length) {
        let child = node?.children;
        child.forEach((item) => {
          childNodeId.push(item.key);
        });
      }
    }
    if (node?.children?.length) {
      getNodeChildId(node?.children, currentId, childNodeId);
    }
  }
  return childNodeId;
};

//删除节点所在服务
export const deleteServiceListByServiceId = (tree, key, serviceId) => {
  for (let i = 0; i < tree.length; i++) {
    let node = tree[i];
    if (node.key === key) {
      if (node?.serviceAuthList?.length) {
        node.serviceAuthList = node.serviceAuthList.map((item) => {
          if (item.serviceId == serviceId) {
            return { ...item, toDeleteFlag: true };
          } else {
            return item;
          }
        });
      } else {
        node.serviceAuthList = [];
      }
    }
    if (node?.children?.length) {
      deleteServiceListByServiceId(node?.children, key, serviceId);
    }
  }
};

//过滤所在节点的服务
export const cancelServiceListByServiceId = (tree, key, serviceId) => {
  for (let i = 0; i < tree.length; i++) {
    let node = tree[i];
    if (node.key === key) {
      if (node?.serviceAuthList?.length) {
        node.serviceAuthList = node.serviceAuthList.filter((item) => item.serviceId !== serviceId);
      } else {
        node.serviceAuthList = [];
      }
    }
    if (node?.children?.length) {
      cancelServiceListByServiceId(node?.children, key, serviceId);
    }
  }
};